import React, {Component} from 'react';
import {
    Image, StyleSheet, Text, TouchableOpacity, View, AsyncStorage, ScrollView, Alert,
    TextInput
} from 'react-native';
import Toast from '@remobile/react-native-toast';
import {BasicStyle} from "../../../style/BasicStyle";
import {ShopCarStyle} from "../../../style/ShopStyle/ShopCarStyle";
import CountEmitter from './../../utils/event/CountEmitter';
import FetchUtils from './../../utils/FetchUtils';
import utils from './../../utils/utils';
import {ShopDetailStyle} from "../../../style/ShopStyle/ShopDetailStyle";
import Spinner from "react-native-loading-spinner-overlay";

export default class ShopOrder extends Component {
    static navigationOptions = ({navigation, screenProps}) => ({
        headerTitle: "确认订单信息",
        headerStyle: {
            backgroundColor: '#F6F6F6',
        },
        headerTitleStyle: {
            alignSelf: 'center',
            fontSize: utils.setSpText(17),
        },
        headerRight: <TouchableOpacity/>
    });

    constructor(props) {
        super(props);
        this.addressId = '';
        this.consignee = '';
        this.address = '';
        this.telephone = '';
        this.shopCarNum = '';
        this.shopCarSumPrice = '';
        this.state = ({
            loadingStatus: false,
            list: null,
            consignee: '',
            address: '',
            telephone: '',
        });
    }

    componentWillMount() {
        CountEmitter.addListener('ShopCarRefresh', () => {
            /*每次监听事件触发就更新购物车(因为我放在本地存储)*/
            this._getShopCarData();
        });

        CountEmitter.addListener('addressRefresh', () => {
            /*每次监听事件触发就更新购物车(因为我放在本地存储)*/
            this._getAddr();
        });
    }

    componentDidMount() {
        this._getShopCarData();
        this._getAddr();
    }

    componentWillUnmount() {
        CountEmitter.removeListener('ShopCarRefresh', () => {
        });

        CountEmitter.removeListener('addressRefresh', () => {
        });
    }

    render() {
        return (
            <View style={[BasicStyle.containerView, ShopCarStyle.containerView]}>
                <Spinner visible={this.state.loadingStatus} textContent={"正在提交。。。"} textStyle={{color: '#000'}}/>

                {!this.state.list
                    ?
                    <Image resizeMode={'stretch'} source={require('./../../../img/empty_cart_words.png')}/>
                    :
                    null
                }

                {!this.state.list
                    ?
                    <TouchableOpacity style={ShopCarStyle.emptyCarBut} onPress={this._emptyShopCarBut.bind(this)}>
                        <Text style={ShopCarStyle.emptyCarButText}>去商城看看</Text>
                    </TouchableOpacity>
                    :
                    null
                }

                {this.state.list
                    ?
                    <View style={{flex: 1}}>
                        <View style={{height: utils.autoheight(200), alignItems: 'center'}}>
                            <View style={{
                                width: utils.autoWidth(320),
                                marginTop: utils.autoheight(16),
                                backgroundColor: '#FFF',
                                borderColor: '#000',
                                borderWidth: utils.autoWidth(1),
                            }}>
                                <View style={{flexDirection: 'row', alignItems: 'center'}}>
                                    <TextInput style={{flex: 1}}
                                               placeholder="收货人姓名" underlineColorAndroid={'transparent'}>
                                        {this.state.consignee}</TextInput>
                                    {this.state.consignee ?
                                        <TouchableOpacity style={{flexDirection: 'row'}} onPress={() => {
                                            let {navigate} = this.props.navigation;
                                            navigate('AddressListNav')
                                        }
                                        }>
                                            <Text style={BasicStyle.commonFontLittleText}>更换</Text>
                                            <Image source={require('./../../../img/rightpoint.png')}
                                                   style={{
                                                       height: utils.autoheight(13), width: utils.autoWidth(8),
                                                       alignSelf: "center",
                                                       marginLeft: utils.autoWidth(10),
                                                       marginRight: utils.autoWidth(10),
                                                   }}/>
                                        </TouchableOpacity>
                                        :
                                        null
                                    }

                                </View>
                                <TextInput style={{
                                    borderColor: '#000',
                                    borderTopWidth: utils.autoWidth(1),
                                    borderBottomWidth: utils.autoWidth(1),
                                }} placeholder="联系手机"
                                           underlineColorAndroid={'transparent'}>{this.state.telephone}</TextInput>
                                <TextInput style={{borderColor: '#000'}}
                                           placeholder="详细地址"
                                           underlineColorAndroid={'transparent'}>{this.state.address}</TextInput>
                            </View>
                        </View>
                        <ScrollView
                            showsVerticalScrollIndicator={false}
                            showsHorizontalScrollIndicator={false}
                            removeClippedSubviews={false}
                            style={{flex: 1}}
                        >
                            {this._shopCarListItem(this.state.list)}
                        </ScrollView>
                    </View>
                    :
                    null
                }

                {this.state.list
                    ?
                    <View style={{
                        height: utils.autoheight(60),
                        width: utils.screenWidth,
                        backgroundColor: '#FFF',
                        flexDirection: 'row',
                        justifyContent: 'space-between',
                        alignItems: 'center',
                        borderTopWidth: utils.autoheight(1),
                        borderColor: '#B2B2B2'
                    }}>
                        <View style={{marginLeft: utils.autoWidth(10)}}><Text
                            style={{fontSize: utils.setSpText(15), color: '#A0A0A0'}}>总计
                            （{this._getShopCarNum(this.state.list)} 件）：</Text></View>
                        <View style={{flexDirection: 'row', marginRight: utils.autoWidth(10)}}>
                            <Text style={{
                                fontSize: utils.setSpText(23),
                                color: '#D0021B',
                                marginRight: utils.autoWidth(10)
                            }}>¥ {this._getShopCarPrice(this.state.list)}</Text>
                            <TouchableOpacity style={{
                                height: utils.autoheight(40),
                                width: utils.autoWidth(120),
                                backgroundColor: '#D0021B',
                                borderRadius: utils.setSpText(3),
                                justifyContent: 'center',
                                alignItems: 'center'
                            }} onPress={() => {
                                this._confirmOrder();
                            }}>
                                <Text style={{fontSize: utils.setSpText(17), color: '#FFF'}}>确认订单</Text>
                            </TouchableOpacity>
                        </View>
                    </View>
                    :
                    null
                }


            </View>
        );
    }

    /*购物车为空的按钮点击事件*/
    _emptyShopCarBut = () => {
        let {navigate} = this.props.navigation;
        navigate('ShopTab')
    };

    /*购物车列表*/
    _shopCarListItem = (list) => {
        let views = list.map((item, index) => {
            return <View key={index}
                         style={{
                             height: utils.autoheight(100),
                             width: utils.screenWidth,
                             backgroundColor: '#FFF',
                             marginBottom: utils.autoheight(1),
                             flexDirection: 'row'
                         }}
            >
                <Image source={{uri: utils.qiniuUrl + item.proMainImg + utils.qiniu200Url}} style={{
                    width: utils.autoWidth(70),
                    height: utils.autoheight(75),
                    marginLeft: utils.autoWidth(15),
                    marginTop: utils.autoheight(12)
                }}/>
                <View style={{marginLeft: utils.autoWidth(10), marginTop: utils.autoheight(12), flex: 1}}>
                    <Text style={{fontSize: utils.setSpText(17), color: '#000'}}>{item.proName}</Text>
                    <Text style={{
                        fontSize: utils.setSpText(15),
                        color: '#A0A0A0'
                    }}>“{item.proColor}”，“{item.proSize}”</Text>
                    <View style={{flexDirection: 'row', justifyContent: 'space-between'}}>
                        <View style={{flexDirection: 'row'}}>
                            <Text style={{
                                fontSize: utils.setSpText(17),
                                color: '#000'
                            }}>{item.proNowPrice ? "¥ " + utils.toDecimal2(item.proNowPrice) + "  " : " "}</Text>
                            <Text style={{
                                fontSize: utils.setSpText(15),
                                color: '#A0A0A0',
                                textDecorationLine: 'line-through'
                            }}>{item.proOldPrice ? "¥ " + utils.toDecimal2(item.proOldPrice) + "  " : " "}</Text>
                        </View>
                        <View style={{flexDirection: 'row', marginRight: utils.autoWidth(35)}}>
                            <Text style={{
                                fontSize: utils.setSpText(21),
                                color: '#000',
                                marginRight: utils.autoheight(10),
                            }}>X</Text>
                            <Text style={{
                                fontSize: utils.setSpText(21),
                                color: '#000'
                            }}>{item.proNum}</Text>
                        </View>
                    </View>
                </View>
            </View>
        });
        return views;
    };

    /*获取购物车数据*/
    _getShopCarData = () => {
        AsyncStorage.getItem("userId").then((userId) => {
            AsyncStorage.getItem("shopCar_" + userId).then((shopCar) => {
                if (shopCar !== null) {
                    this.setState({
                        list: JSON.parse(shopCar),
                    })
                }
            })

        })
    };
    /*计算购物车件数*/
    _getShopCarNum = (list) => {
        let sum = 0;
        for (let n = 0; n < list.length; n++) {
            sum = parseInt(list[n].proNum) + parseInt(sum);
        }
        this.shopCarNum = sum;
        return sum
    };
    /*计算购物车总价*/
    _getShopCarPrice = (list) => {
        let sum = 0;
        for (let n = 0; n < list.length; n++) {
            sum = parseFloat(list[n].proNowPrice) * parseInt(list[n].proNum) + parseFloat(sum);
        }
        this.shopCarSumPrice = sum;
        return utils.toDecimal2(sum)
    };

    /*获取地址数据*/
    _getAddr = () => {
        AsyncStorage.getItem("XToken").then((xToken) => {
            FetchUtils.getWithHeader(utils.apiUrl + '/user/defaultaddress', xToken, '', (res) => {
                console.log(res);
                if (res.code === 200) {
                    this.setState({
                        consignee: res.apiData.consignee,
                        address: res.apiData.address,
                        telephone: res.apiData.telephone,
                        addressId: res.apiData.id,
                    })
                } else {
                    Toast.showShortBottom("错误：" + res.apiData);
                }
            });
        });
    };

    /*确认订单*/
    _confirmOrder = () => {
        this.setState({
            loadingStatus: true,
        });
        AsyncStorage.getItem("XToken").then((xToken) => {
            let params = {
                productList: this.state.list,
                consignee: this.state.consignee,
                address: this.state.address,
                telephone: this.state.telephone,
                shopCarNum: this.shopCarNum,
                shopCarSumPrice: this.shopCarSumPrice,
            };
            FetchUtils.postWithParamHeader(utils.apiUrl + '/order/create', params, xToken, (res) => {
                if (res.code !== 200) {
                    Toast.showShortBottom("操作错误：" + res.apiData);
                    this.setState({
                        loadingStatus: false
                    })
                } else {
                    Toast.showShortBottom("操作成功");
                    this._emptyShopCar();//清空购物车
                    CountEmitter.emit("ShopCarRefresh");//刷新购物车
                    let {navigate} = this.props.navigation;
                    navigate('ShopOrderPayNav', {orderId: res.apiData.id});
                    this.setState({
                        loadingStatus: false
                    });
                }
            });
        });


    };

    /*清空购物车*/
    _emptyShopCar = () => {
        AsyncStorage.getItem("userId").then((userId) => {
            AsyncStorage.setItem("shopCar_" + userId, JSON.stringify(null), (error) => {
                if (error) {
                    console.log(error);
                }
            })
        })
    }

}
;